/**
 * @website http://carrollfuel.com/
 * @description This file contains functions related to the Carroll Fuels Report System
 * @date 21/11/2013
 * @author Gabriel Villalobos, Karol Leal
 * @version 1.0
 * @dependencies jQuery
 * Copyright(c) 2013 www.dynamis-soft.com
 */
 var Carroll = Carroll || {};

Carroll.ReportManager = Carroll.ReportManager || {};

Carroll.ReportManager.UIManager = function(){

    var cache = {
        formReport                  : $('#report-form'),
        fromDate                    : $('#from'),
        toDate                  	: $('#to'),
        tank      					: $('#tank'),
        htmlBtn          			: $('#html-btn'),
        pdfBtn              		: $('#pdf-btn'),
        xlsBtn               		: $('#xls-btn'),
        dataResponse				: $('#data-response'),
        inputData					: $('#html-data'),
        userList					: $('#users-list'),
        userInput					: $('#user-edit'),
        usersBtn					: $('#open-modal-users'),
        formEdit					: $('#edit-form'),
        tanksForm					: $('#tanks-form'),
        inventoryForm				: $('#inventory-form'),
        addBtn						: $('#add-btn')
    };

    var cacheForm = {
    	idEdit 					: $('#id-edit'),
    	dateEdit				: $('#date-edit'),
    	productEdit				: $('#product-edit'),
    	gallonsEdit				: $('#gallons-edit'),
    	waterEdit				: $('#water-edit'),
    	salesEdit				: $('#sales-edit'),
    	grossEdit				: $('#gross-edit'),
    	soEdit					: $('#so-edit'),
    	saEdit					: $('#sa-edit'),
    	tankEdit				: $('#tank-edit'),
    	hosesEdit				: $('#hoses-edit'),
    	nozzlesEdit				: $('#nozzles-edit'),
    	dispensersEdit			: $('#dispensers-edit'),
    	commentsEdit			: $('#comments-edit'),
        saveBtn					: $('#save-edit'),
        closeBtn				: $('#close-edit')        
    };

    var tankCacheForm = {
    	tankID1					: $('#tanks-id-1'),
    	tankID2					: $('#tanks-id-2'),
    	tankID3					: $('#tanks-id-3'),
    	tankProduct1			: $('#tanks-select-1'),
    	tankProduct2			: $('#tanks-select-2'),
    	tankProduct3			: $('#tanks-select-3'),
    	tankQty1				: $('#tanks-gallons-1'),
    	tankQty2				: $('#tanks-gallons-2'),
    	tankQty3				: $('#tanks-gallons-3'),
    	tankBlenderOpt			: $('#modal-tanks').find('input[name=tanks-blender]:radio'),
    	tankBlenderVal			: $('#tanks-midgrade-type'),
    	saveTankBtn				: $('#save-tanks')
    };

    var inventoryCacheForm = {
    	tankID					: $('#inventory-tank-id'),
    	tankSize				: $('#inventory-tank-size'),
    	productInventory		: $('#inventory-select-1'),
    	inventoryBlenderOpt		: $('#inventory-form').find('input[name=inventory-blender]:radio'),
    	inventoryBlenderType	: $('#inventory-blender-type'),
    	inventoryManifoldOpt	: $('#inventory-form').find('input[name=inventory-manifold]:radio'),
    	inventoryTankNo			: $('#inventory-tank-no'),
    	inventoryAlertOpt		: $('#inventory-notifications'),
    	saveInventoryBtn		: $('#save-inventory')
    };

    var tankValues = {
    	'BCD8091EBFE8483AA7749DC7CF66C23C' : 'CLR DSL',
    	'F2858F8E8A93474698407F080CD6B061' : 'GASOLINE 87 OCT E-10 UNLEADED',
    	'CA7200DE3FFD4C24BC7BC2C5F6EBD787' : 'GASOLINE 93 OCT E-10 HITEST'
    };

    var that		= this;
    var listener	= new Carroll.ReportManager.Listener(cache, cacheForm, tankCacheForm, inventoryCacheForm, this);

    this.initialize = function(){
    	listener.initialize();
    };

    this.resetForm = function(){
    	cache.formEdit[0].reset();
		cache.formEdit.find('input[type=text], input[type=password], input[type=number], input[type=email], textarea').val('');
    };
	
    this.resetTanks = function(){
    	cache.tanksForm[0].reset();
		cache.tanksForm.find('input[type=text]').val('');
    };

    this.resetInventory = function(){
    	cache.inventoryForm[0].reset();
		cache.inventoryForm.find('input[type=text]').val('');
    };

	this.checkDailyInfo = function(){
		$.ajax({
		    type: "POST",
		    url:  "checkDay.php",
		    success: function(data) {
				if (data.trim() == "") {
					cacheForm.commentsEdit.removeAttr('disabled');
				} else {
					$('#id-edit').val(data.trim());
					that.sendEditForm('getInfo');
				}
		    },
		    error: function (xhr, ajaxOptions, thrownError) {
		        console.log(xhr.status);
	      	}
		});		
		//
	};

	this.checkTanks = function(){
		var userId = cache.userInput.val();
		$.ajax({
		    type: "POST",
		    url:  "tanksetup.php",
		    data: {
		    	'checkTanks' : '1',
		    	'userId' : userId
		    },
		    success: function(data) {
				if (data.trim() != "") {
					that.displayTanks(data);
				}
		    },
		    error: function (xhr, ajaxOptions, thrownError) {
		        console.log(xhr.status);
	      	}
		});		
		//
	};

    this.sendEditForm = function(path){
		$.ajax({
		    type: "POST",
		    data: cache.formEdit.serialize(),
		    url:  path + ".php",
		    success: function(data) {
		        that.fillEditForm(data);
		    },
		    error: function (xhr, ajaxOptions, thrownError) {
		        console.log(xhr.status);
	      	}
		});
    };

    this.saveForm = function(path){
		$.ajax({
		    type: "POST",
		    data: cache.formEdit.serialize(),
		    url:  path + ".php",
		    success: function(data) {
		    	$('#modal-edit').modal('hide');
		        that.resetForm();
		    },
		    error: function (xhr, ajaxOptions, thrownError) {
		        console.log(xhr.status);
	      	}
		});
    };

    this.saveTanks = function(){
		$.ajax({
		    type: "POST",
		    data: cache.tanksForm.serialize(),
		    url:  "tanksetup.php",
		    success: function(data) {
		    	$('#tanks-form').modal('hide');
		        that.resetTanks();
		    },
		    error: function (xhr, ajaxOptions, thrownError) {
		        console.log(xhr.status);
	      	}
		});
    };

    this.saveInventory = function(){
		$.ajax({
		    type: "POST",
		    data: cache.inventoryForm.serialize(),
		    url:  "inventorysetup.php",
		    success: function(data) {
		    	$('#inventory-form').modal('hide');
		        that.resetInventory();
		    },
		    error: function (xhr, ajaxOptions, thrownError) {
		        console.log(xhr.status);
	      	}
		});
    };


    this.selectUser = function(event){
    	event.preventDefault();
    	var id = $(event.currentTarget).attr('data-id');
    	cache.userInput.val(id);
    	$('#modal-users').modal('hide');

    };

    this.getUsersList = function(){
		$.ajax({
		    type: "GET",
		    url:  "userslist.php",
		    success: function(data) {
		    	//that.displayUsers(data);
		    },
		    error: function (xhr, ajaxOptions, thrownError) {
		        console.log(xhr.status);
	      	}
		});
    };

    this.displayUsers = function(users){
    	var usersTpl = "";
        for(var i = 0; i < users.length; i++){
            usersTpl += _.template($('#tpl-users-list').html(), {
            	id: users[i].id,
            	name: users[i].name
            });
        }
        cache.userList.html(usersTpl);
    };

    this.displayTanks = function(tanks){
    	var idTemp = 1;
    	for (var i = 0; i < tanks.length; i++) {
    		$('#tanks-id-'+idTemp).val(tanks[i].TankID.trim());
    		$('#tanks-select-'+idTemp).val(tanks[i].Product.trim());
    		$('#tanks-gallons-'+idTemp).val(tanks[i].TankID.trim());
    		idTemp++;
    	};
    };

    this.fillEditForm = function(data){
    	var newData = JSON.parse(data);
    	cacheForm.dateEdit.val(newData.DateEntry.trim());
    	cacheForm.productEdit.val(newData.Product.trim());
    	cacheForm.gallonsEdit.val(newData.OpeningGallons.trim());
    	cacheForm.waterEdit.val(newData.Water.trim());
    	cacheForm.salesEdit.val(newData.Sales.trim());
    	cacheForm.grossEdit.val(newData.GrossDeliveries.trim());
    	cacheForm.tankEdit.val(tankValues[newData.Tank.trim()]);
    	cacheForm.soEdit.val(newData.Operating.trim());
    	cacheForm.saEdit.val(newData.Alarm.trim());
    	cacheForm.hosesEdit.val(newData.Hoses.trim());
    	cacheForm.nozzlesEdit.val(newData.Nozzles.trim());
    	cacheForm.dispensersEdit.val(newData.Dispensers.trim());
    	cacheForm.commentsEdit.text(newData.Commets.trim());
		cacheForm.commentsEdit.attr('disabled','disabled');
    };
};

Carroll.ReportManager.Listener = function(cache, cacheForm, tankCacheForm, inventoryCacheForm, UIManager){

	var bindingElements = function(){

		cache.htmlBtn.on('click', function(event){
			event.preventDefault();
			$(event.currentTarget).toggleClass('active');
			var action = $(event.currentTarget).attr('dir');
			$.ajax({
			    type: 'POST',
			    data: cache.formReport.serialize(),
			    url:  action,
			    success: function(data) {
			        cache.dataResponse.html(data);
			        cache.pdfBtn.removeAttr("disabled");
			        cache.xlsBtn.removeAttr("disabled");
			        $(event.currentTarget).toggleClass('active');
			    },
			    error: function (xhr, ajaxOptions, thrownError) {
			        console.log(xhr.status);
			        cache.dataResponse.html(thrownError);
			        $(event.currentTarget).toggleClass('active');
		      	}
			});
		});

		cache.pdfBtn.on('click', function(event){
			event.preventDefault();
			cache.inputData.val(cache.dataResponse.html());
			cache.formReport.attr('target','_blank');
			cache.formReport.attr('action', $(event.currentTarget).attr('dir'));
			cache.formReport.submit();
		});

		cache.xlsBtn.on('click', function(event){
			event.preventDefault();
			cache.inputData.val(cache.dataResponse.html());
			cache.formReport.attr('target','_blank');
			cache.formReport.attr('action', $(event.currentTarget).attr('dir'));
			cache.formReport.submit();
		});

		cache.dataResponse.on('click', 'table a.edit', function(event){
			event.preventDefault();
			var id = $(event.currentTarget).attr('data-id');
			$('#id-edit').val(id);
			//cacheForm.tankEdit.attr('readonly', true);
			UIManager.sendEditForm('getInfo');
		});

		cache.addBtn.on('click', $.proxy(UIManager.checkDailyInfo, UIManager));

		cache.userList.on('click', 'a', $.proxy(UIManager.selectUser, UIManager));

		cache.usersBtn.on('click', $.proxy(UIManager.getUsersList, UIManager));
		
		cacheForm.saveBtn.on('click', $.proxy(UIManager.saveForm, UIManager, 'mantenimiento'));

		cacheForm.closeBtn.on('click', $.proxy(UIManager.resetForm, UIManager));

		tankCacheForm.saveTankBtn.on('click', $.proxy(UIManager.saveTanks, UIManager));

		inventoryCacheForm.saveInventoryBtn.on('click', $.proxy(UIManager.saveInventory, UIManager));
		
	};

	this.initialize = function(){
		bindingElements();
		cache.fromDate.datepicker({'dateFormat':'mm-dd-yy'});
		cache.toDate.datepicker({'dateFormat':'mm-dd-yy'});
	};
};

$(document).ready(function(){
    //Initializes the UIManager once the Document is Ready
    var uiManager = new Carroll.ReportManager.UIManager();
    uiManager.initialize();
});